package com.aplink.generic.google.datetimepicker;

import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;

/**
 * A simple utility class to handle haptic feedback.
 */
public class HapticFeedbackController {
    private static final int VIBRATE_DELAY_MS = 125;
    private static final int VIBRATE_LENGTH_MS = 5;

    private static boolean checkGlobalSetting(final Context context) {
        return Settings.System.getInt(context.getContentResolver(),
                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 1;
    }

    private final ContentObserver mContentObserver;
    private final Context mContext;

    private boolean mIsGloballyEnabled;
    private long mLastVibrate;

    private Vibrator mVibrator;

    public HapticFeedbackController(final Context context) {
        this.mContext = context;
        this.mContentObserver = new ContentObserver(null) {
            @Override
            public void onChange(final boolean selfChange) {
                HapticFeedbackController.this.mIsGloballyEnabled = HapticFeedbackController
                        .checkGlobalSetting(HapticFeedbackController.this.mContext);
            }
        };
    }

    /**
     * Call to setup the controller.
     */
    public void start() {
        this.mVibrator = (Vibrator) this.mContext
                .getSystemService(Context.VIBRATOR_SERVICE);

        // Setup a listener for changes in haptic feedback settings
        this.mIsGloballyEnabled = HapticFeedbackController
                .checkGlobalSetting(this.mContext);
        final Uri uri = Settings.System
                .getUriFor(Settings.System.HAPTIC_FEEDBACK_ENABLED);
        this.mContext.getContentResolver().registerContentObserver(uri, false,
                this.mContentObserver);
    }

    /**
     * Call this when you don't need the controller anymore.
     */
    public void stop() {
        this.mVibrator = null;
        this.mContext.getContentResolver().unregisterContentObserver(
                this.mContentObserver);
    }

    /**
     * Try to vibrate. To prevent this becoming a single continuous vibration,
     * nothing will happen if we have vibrated very recently.
     */
    public void tryVibrate() {
        if ((this.mVibrator != null) && this.mIsGloballyEnabled) {
            final long now = SystemClock.uptimeMillis();
            // We want to try to vibrate each individual tick discretely.
            if ((now - this.mLastVibrate) >= HapticFeedbackController.VIBRATE_DELAY_MS) {
                this.mVibrator
                        .vibrate(HapticFeedbackController.VIBRATE_LENGTH_MS);
                this.mLastVibrate = now;
            }
        }
    }
}
